using System;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;

namespace SharePoint2010Poll
{
    /// <summary>
    /// This class handles events raised during feature activation, deactivation, installation, uninstallation, and upgrade.
    /// </summary>
    /// <remarks>
    /// The GUID attached to this class may be used during packaging and should not be modified.
    /// </remarks>

    [Guid("133c83e4-de5d-4009-89e4-50b5854c22ae")]
    public class PollWebPartEventReceiver : SPFeatureReceiver
    {
        const string PollListName = "Polls";
        //const string PollAnswersListName = "PollAnswers";
        const string PollUserResponseListName = "PollUserResponses";

        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            SPSite site = properties.Feature.Parent as SPSite;

            if (site != null)
            {
                CreateListFramework(site);
            }
        }

        private void CreateListFramework(SPSite site)
        {
            Guid pollListId = site.RootWeb.Lists.Add(PollListName, "Contains all Polls", SPListTemplateType.GenericList);
            SPList pollList = site.RootWeb.Lists[pollListId];
            pollList.Fields.Add("PollId", SPFieldType.Text, true);
            pollList.Fields.Add("Question", SPFieldType.Text, true);
            pollList.Fields.Add("Answers", SPFieldType.Note, true);
            pollList.Update();           

            Guid pollResponsesListId = site.RootWeb.Lists.Add(PollUserResponseListName, "Contains all Poll user responses", SPListTemplateType.GenericList);
            SPList pollUserResponseList = site.RootWeb.Lists[pollResponsesListId];
            pollUserResponseList.Fields.Add("PollId", SPFieldType.Text, true);
            pollUserResponseList.Fields.Add("Answer", SPFieldType.Text, true);
            pollUserResponseList.Fields.Add("UserId", SPFieldType.Text, true);
            pollUserResponseList.Update();
        }

        private void DeleteListFramework(SPSite site)
        {
            SPList listToDelete = site.RootWeb.Lists.TryGetList(PollListName);

            if (listToDelete != null)
            {
                listToDelete.Delete();

            }           

            listToDelete = site.RootWeb.Lists.TryGetList(PollUserResponseListName);

            if (listToDelete != null)
            {
                listToDelete.Delete();

            }

        }
       
        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            SPSite site = properties.Feature.Parent as SPSite;

            if (site != null)
            {
                DeleteListFramework(site);
            }
        }      
    }
}
